<?php

/*
 * Fresns Control Panel (Standalone)
 * Copyright (C) 2021-Present 刘鑫
 * Released under the MIT License.
 */

namespace App\Plugins\FcpApi\Base;

use App\Base\Controllers\BaseApiController;
use App\Http\Center\Common\ErrorCodeService;
use App\Http\Center\Common\LogService;
use App\Http\Center\Helper\PluginHelper;
use App\Http\Center\Helper\CmdRpcHelper;
use App\Http\FresnsCmd\FresnsCmdWords;
use App\Http\FresnsCmd\FresnsCmdWordsConfig;
use App\Http\FresnsDb\FresnsSessionKeys\FresnsSessionKeys;
use Illuminate\Support\Facades\Request;

class TweetBaseController extends BaseApiController
{
    public $appId;

    public $langTag;

    public $sign;

    public $platform;
    public $version;
    public $versionInt;
    public $uid;
    public $mid;
    public $token;

    //是否开启签名验证: true 开启，false 关闭
    public $checkSign = false;

    public function __construct()
    {
        $this->checkRequest();
    }

    public function checkRequest()
    {
        $pluginUniKey = 'FcpApi';
        // 执行上传
        $pluginClass = PluginHelper::findPluginClass($pluginUniKey);

        if (empty($pluginClass)) {
            LogService::error('未找到插件类');
            $this->error(ErrorCodeService::PLUGIN_UNIKEY_ERROR);
        }

        $isPlugin = PluginHelper::pluginCanUse($pluginUniKey);
        if ($isPlugin == false) {
            LogService::error('未找到插件类');
            $this->error(ErrorCodeService::PLUGIN_UNIKEY_ERROR);
        }
        if ($this->checkSign) {
            $uri = Request::getRequestUri();
            if ($uri !== '/api/admin/adminLogin') {
                $this->checkSign();
            }
        }

        return true;
    }

    // 验证签名
    // 第一步，设所有发送或者接收到的数据为集合M，将集合M内非空参数值的参数按照参数名ASCII码从小到大排序（字典序），使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串stringA。
    // 第二步，在stringA最后拼接上key得到stringSignTemp字符串，并对stringSignTemp进行MD5运算，再将得到的字符串所有字符转换为大写，得到sign值signValue。
    public function checkSign()
    {
        $appId = request()->header('appId');
        $platform = request()->header('platform');
        if (! is_numeric($platform)) {
            $info = [
                'platform' => '请输入整数',
            ];
            $this->error(ErrorCodeService::HEADER_INFO_ERROR, $info);
        }

        //1、验证 appId 和 platform 参数
        //1.1、是否存在 session_keys > app_id
        //1.2、是否匹配 platsession_keys > platform_id
        //1.3、是否启用 session_keys > is_enable
        $sessionKeys = FresnsSessionKeys::where('app_id', $appId)->first();

        if (empty($sessionKeys)) {
            $info = [
                'appId' => '无此记录',
            ];

            $this->error(ErrorCodeService::HEADER_INFO_ERROR, $info);
        }
        if ($sessionKeys['platform_id'] != $platform) {
            $info = [
                'platform' => '无此记录',
            ];

            $this->error(ErrorCodeService::HEADER_INFO_ERROR, $info);
        }
        if ($sessionKeys['is_enable'] == 0) {
            $this->error(ErrorCodeService::TOKEN_IS_ENABLE_ERROR);
        }
        if ($sessionKeys['type'] == 1) {
            $this->error(ErrorCodeService::HEADER_KEY_ERROR);
        }

        $dataMap = [];
        foreach (FsConfig::SIGN_FIELD_ARR as $signField) {
            $signFieldValue = request()->header($signField);
            if (! empty($signFieldValue)) {
                $dataMap[$signField] = $signFieldValue;
            }
        }

        $dataMap['sign'] = request()->header('sign');
        LogService::info('验签信息: ', $dataMap);

        $cmd = FresnsPluginConfig::FRESNS_CMD_VERIFY_SIGN;

        $resp = CmdRpcHelper::call(FresnsPlugin::class, $cmd, $dataMap);
        if (CmdRpcHelper::isErrorCmdResp($resp)) {
            $this->errorCheckInfo($resp, [], $resp['output']);
        }

        return true;
    }
}
